import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../providers/anime_provider.dart';
import '../providers/favorite_provider.dart';
import '../widgets/favorite_button.dart';
import '../../domain/entities/anime.dart';
import '../../core/utils/chinese_title_mapper.dart';

/// 动漫详情页面
class DetailPage extends StatefulWidget {
  const DetailPage({super.key});

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  late int animeId;
  Anime? anime;
  bool isLoading = true;
  List<Anime> recommendations = [];
  bool isLoadingRecommendations = false;
  
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 从路由参数获取动漫ID
    final args = ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    animeId = args?['id'] ?? 1;
    _loadAnimeDetails();
  }

  Future<void> _loadAnimeDetails() async {
    setState(() => isLoading = true);
    final provider = Provider.of<AnimeProvider>(context, listen: false);
    final result = await provider.getAnimeDetails(animeId);
    setState(() {
      anime = result;
      isLoading = false;
    });
    
    // 加载完动漫详情后，获取推荐
    if (result != null) {
      _loadRecommendations();
    }
  }

  Future<void> _loadRecommendations() async {
    if (anime == null) return;
    
    setState(() => isLoadingRecommendations = true);
    final provider = Provider.of<AnimeProvider>(context, listen: false);
    final result = await provider.getSmartRecommendations(anime!);
    setState(() {
      recommendations = result;
      isLoadingRecommendations = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: const Center(child: CircularProgressIndicator()),
      );
    }

    if (anime == null) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: const Center(
          child: Text('动漫详情加载失败'),
        ),
      );
    }

    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 简化的AppBar
          SliverAppBar(
            pinned: true,
            backgroundColor: Colors.white,
            elevation: 1,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.black),
              onPressed: () => Navigator.pop(context),
            ),
            actions: [
              // 使用真正的收藏按钮
              if (anime != null)
                FavoriteButton(
                  anime: anime!,
                  onFavoriteChanged: () {
                    // 可以在这里处理收藏状态变化后的逻辑
                  },
                ),
              IconButton(
                icon: Icon(Icons.share, color: Colors.grey[600]),
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('分享功能开发中'),
                      duration: Duration(seconds: 1),
                    ),
                  );
                },
              ),
            ],
          ),
          
          // 主要内容区域 - 图片和信息的左右布局
          SliverToBoxAdapter(
            child: _buildMainContent(),
          ),
          
          // 操作按钮区域
          SliverToBoxAdapter(
            child: _buildActionButtons(),
          ),
          
          // 简介区域
          SliverToBoxAdapter(
            child: _buildSynopsisSection(),
          ),
          
          // 集数列表
          SliverToBoxAdapter(
            child: _buildEpisodesList(),
          ),
          
          // 相关推荐
          SliverToBoxAdapter(
            child: _buildRecommendations(),
          ),
          
          // 底部安全区域
          const SliverToBoxAdapter(
            child: SizedBox(height: 32),
          ),
        ],
      ),
    );
  }

  Widget _buildMainContent() {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime!.title,
      titleJapanese: anime!.titleJapanese,
      titleEnglish: anime!.titleEnglish,
      titleSynonyms: anime!.titleSynonyms,
    );
    final chineseGenres = ChineseTitleMapper.getChineseGenres(anime!.genres);

    return Container(
      padding: const EdgeInsets.all(16),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final isWideScreen = constraints.maxWidth > 600;
          
          if (isWideScreen) {
            // 大屏幕：使用水平布局
            return Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧图片区域
          Expanded(
            flex: 2,
            child: _buildImageArea(),
          ),
          
          const SizedBox(width: 16),
          
          // 右侧信息区域
          Expanded(
            flex: 3,
                  child: _buildInfoArea(chineseTitle, chineseGenres),
                ),
              ],
            );
          } else {
            // 手机端：使用垂直布局
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 顶部图片和基本信息
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 左侧封面（更小尺寸）
                    SizedBox(
                      width: 120,
                      height: 160,
                      child: _buildImageArea(),
                    ),
                    
                    const SizedBox(width: 12),
                    
                    // 右侧基本信息
                    Expanded(
            child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 标题
                          Text(
                            chineseTitle,
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF2C3E50),
                            ),
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ),
                          
                          // 日文标题
                          if (anime!.titleJapanese.isNotEmpty && anime!.titleJapanese != chineseTitle) ...[
                            const SizedBox(height: 4),
                            Text(
                              anime!.titleJapanese,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[600],
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                          
                          const SizedBox(height: 8),
                          
                          // 评分
                          if (anime!.score > 0) ...[
                            Row(
                              children: [
                                Icon(Icons.star, color: _getScoreColor(anime!.score), size: 16),
                                const SizedBox(width: 4),
                                Text(
                                  anime!.score.toStringAsFixed(1),
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                    color: _getScoreColor(anime!.score),
                                  ),
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  _getScoreDescription(anime!.score),
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey[600],
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),
                          ],
                          
                          // 排名信息（简化）
                          if (anime!.ranked != null) ...[
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.amber.withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(6),
                              ),
                              child: Text(
                                '排名 #${anime!.ranked}',
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.amber[700],
                                ),
                              ),
                            ),
                            const SizedBox(height: 4),
                          ],
                          
                          // 人气排名
                          if (anime!.popularity != null) ...[
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.purple.withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(6),
                              ),
                              child: Text(
                                '人气 #${anime!.popularity}',
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.purple[700],
                                ),
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ],
                ),
                
                const SizedBox(height: 16),
                
                // 成员和收藏信息
                if (anime!.members != null || anime!.favorites != null) ...[
                  Row(
                    children: [
                      if (anime!.members != null) ...[
                        Icon(Icons.people, size: 16, color: Colors.grey[600]),
                        const SizedBox(width: 4),
                        Text(
                          '${_formatNumber(anime!.members!)} 成员',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(width: 16),
                      ],
                      if (anime!.favorites != null) ...[
                        Icon(Icons.favorite, size: 16, color: Colors.red[400]),
                        const SizedBox(width: 4),
                        Text(
                          '${_formatNumber(anime!.favorites!)} 收藏',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ],
                  ),
                  const SizedBox(height: 12),
                ],
                
                // 状态和分类标签
                Wrap(
                  spacing: 6,
                  runSpacing: 6,
                  children: [
                    if (anime!.status.isNotEmpty)
                      _buildInfoChip(
                        _getStatusText(anime!.status),
                        _getStatusColor(anime!.status),
                      ),
                    if (anime!.year != null)
                      _buildInfoChip('${anime!.year}年', Colors.blue),
                    if (anime!.episodes > 0)
                      _buildInfoChip('${anime!.episodes}话', Colors.green),
                    if (anime!.rating != null && anime!.rating!.isNotEmpty)
                      _buildInfoChip(_getRatingText(anime!.rating!), Colors.red),
                    ...chineseGenres.take(3).map(
                      (genre) => _buildInfoChip(genre, Colors.orange),
                    ),
                  ],
                ),
                
                const SizedBox(height: 16),
                
                // 详细信息
                _buildDetailedInfo(),
              ],
            );
          }
        },
      ),
    );
  }

  Widget _buildInfoArea(String chineseTitle, List<String> chineseGenres) {
    return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text(
                  chineseTitle,
                  style: const TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF2C3E50),
                  ),
                ),
                
                // 日文标题（如果不同）
                if (anime!.titleJapanese.isNotEmpty && anime!.titleJapanese != chineseTitle) ...[
                  const SizedBox(height: 4),
                  Text(
                    anime!.titleJapanese,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
                
                const SizedBox(height: 12),
                
                // 评分
                if (anime!.score > 0) ...[
                  Row(
                    children: [
                      Icon(Icons.star, color: _getScoreColor(anime!.score), size: 20),
                      const SizedBox(width: 4),
                      Text(
                        anime!.score.toStringAsFixed(1),
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: _getScoreColor(anime!.score),
                        ),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        _getScoreDescription(anime!.score),
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                ],
                
                // 排名和人气信息
                Row(
                  children: [
                    if (anime!.ranked != null) ...[
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.amber.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.emoji_events, size: 14, color: Colors.amber[700]),
                            const SizedBox(width: 4),
                            Text(
                              '排名 #${anime!.ranked}',
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.w600,
                                color: Colors.amber[700],
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(width: 8),
                    ],
                    if (anime!.popularity != null) ...[
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.purple.withValues(alpha: 0.1),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.trending_up, size: 14, color: Colors.purple[700]),
                            const SizedBox(width: 4),
                            Text(
                              '人气 #${anime!.popularity}',
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.w600,
                                color: Colors.purple[700],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ],
                ),
                
                const SizedBox(height: 12),
                
                // 成员和收藏数
                if (anime!.members != null || anime!.favorites != null) ...[
                  Row(
                    children: [
                      if (anime!.members != null) ...[
                        Icon(Icons.people, size: 16, color: Colors.grey[600]),
                        const SizedBox(width: 4),
                        Text(
                          '${_formatNumber(anime!.members!)} 成员',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(width: 16),
                      ],
                      if (anime!.favorites != null) ...[
                        Icon(Icons.favorite, size: 16, color: Colors.red[400]),
                        const SizedBox(width: 4),
                        Text(
                          '${_formatNumber(anime!.favorites!)} 收藏',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ],
                  ),
                  const SizedBox(height: 12),
                ],
                
        // 状态和分类标签
                Wrap(
                  spacing: 6,
                  runSpacing: 6,
                  children: [
                    if (anime!.status.isNotEmpty)
                      _buildInfoChip(
                        _getStatusText(anime!.status),
                        _getStatusColor(anime!.status),
                      ),
                    if (anime!.year != null)
                      _buildInfoChip('${anime!.year}年', Colors.blue),
                    if (anime!.episodes > 0)
                      _buildInfoChip('${anime!.episodes}话', Colors.green),
                    if (anime!.rating != null && anime!.rating!.isNotEmpty)
                      _buildInfoChip(_getRatingText(anime!.rating!), Colors.red),
                    ...chineseGenres.take(3).map(
                      (genre) => _buildInfoChip(genre, Colors.orange),
                    ),
                  ],
                ),
                
                const SizedBox(height: 16),
                
        // 详细信息
        _buildDetailedInfo(),
      ],
    );
  }

  Widget _buildDetailedInfo() {
    return Column(
      children: [
                // 详细信息
                if (anime!.studios.isNotEmpty) ...[
                  _buildDetailInfoRow(
                    icon: Icons.business,
                    label: '制作公司',
                    value: anime!.studios.join(' · '),
                  ),
                  const SizedBox(height: 8),
                ],
                
                if (anime!.aired != null && anime!.aired!.isNotEmpty) ...[
                  _buildDetailInfoRow(
                    icon: Icons.calendar_today,
                    label: '播出时间',
                    value: _formatAiredTime(anime!.aired!),
                  ),
                  const SizedBox(height: 8),
                ],
                
                if (anime!.season.isNotEmpty && anime!.season != '未知') ...[
                  _buildDetailInfoRow(
                    icon: Icons.schedule,
                    label: '播出季度',
                    value: '${anime!.year ?? ''}年${_getSeasonText(anime!.season)}',
                  ),
                  const SizedBox(height: 8),
                ],
                
                if (anime!.url != null && anime!.url!.isNotEmpty) ...[
                  _buildDetailInfoRow(
                    icon: Icons.link,
                    label: 'MAL链接',
                    value: 'MyAnimeList页面',
                    isLink: true,
                    onTap: () {
                      // TODO: 打开链接
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('功能开发中'),
                          duration: Duration(seconds: 1),
                        ),
                      );
                    },
                  ),
                  const SizedBox(height: 8),
                ],
                
                if (anime!.trailer != null && anime!.trailer!.isNotEmpty) ...[
                  _buildDetailInfoRow(
                    icon: Icons.play_circle,
                    label: '预告片',
                    value: '观看预告片',
                    isLink: true,
                    onTap: () {
                      // TODO: 播放预告片
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('预告片播放功能开发中'),
                          duration: Duration(seconds: 1),
                        ),
                      );
                    },
                  ),
                ],
              ],
    );
  }

  Widget _buildImageArea() {
    return AspectRatio(
      aspectRatio: 3/4, // 标准动漫海报比例
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.2),
              blurRadius: 10,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: anime!.imageUrl.isNotEmpty
              ? Stack(
                  children: [
                    CachedNetworkImage(
                      imageUrl: anime!.imageUrl,
                      width: double.infinity,
                      height: double.infinity,
                      fit: BoxFit.cover,
                      placeholder: (context, url) => Container(
                        color: Colors.grey[300],
                        child: const Center(
                          child: CircularProgressIndicator(),
                        ),
                      ),
                      errorWidget: (context, url, error) => Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              _getThemeColor(anime!.id),
                              _getThemeColor(anime!.id).withValues(alpha: 0.7),
                            ],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                        ),
                        child: const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.image_not_supported, size: 40, color: Colors.white),
                              SizedBox(height: 8),
                              Text(
                                '图片加载失败',
                                style: TextStyle(color: Colors.white, fontSize: 12),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    // 点击放大功能
                    Positioned.fill(
                      child: Material(
                        color: Colors.transparent,
                        child: InkWell(
                          borderRadius: BorderRadius.circular(12),
                          onTap: () => _showFullScreenImage(),
                          child: Container(
                            alignment: Alignment.bottomRight,
                            padding: const EdgeInsets.all(8),
                            child: Container(
                              padding: const EdgeInsets.all(4),
                              decoration: BoxDecoration(
                                color: Colors.black.withValues(alpha: 0.6),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: const Icon(
                                Icons.fullscreen,
                                color: Colors.white,
                                size: 16,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                )
              : Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        _getThemeColor(anime!.id),
                        _getThemeColor(anime!.id).withValues(alpha: 0.7),
                      ],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                  ),
                  child: const Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.image, size: 40, color: Colors.white),
                        SizedBox(height: 8),
                        Text(
                          '暂无封面',
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ],
                    ),
                  ),
                ),
        ),
      ),
    );
  }

  Widget _buildActionButtons() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final isWideScreen = constraints.maxWidth > 600;
            
            if (isWideScreen) {
              // 大屏幕：水平排列
              return Row(
        children: [
          Expanded(
            flex: 2,
                    child: _buildPlayButton(),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: _buildFavoriteButton(),
                  ),
                ],
              );
            } else {
              // 手机端：垂直排列或优化水平排列
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 主要操作按钮
                  Row(
                    children: [
                      Expanded(
                        flex: 3,
                        child: _buildPlayButton(),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        flex: 2,
                        child: _buildFavoriteButton(),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  // 次要操作按钮
                  Row(
                    children: [
                      Expanded(
                        child: _buildSecondaryButton(
                          icon: Icons.share,
                          label: '分享',
                          onPressed: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('分享功能开发中'),
                                duration: Duration(seconds: 1),
                              ),
                            );
                          },
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: _buildSecondaryButton(
                          icon: Icons.download,
                          label: '缓存',
                          onPressed: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('缓存功能开发中'),
                                duration: Duration(seconds: 1),
                              ),
                            );
                          },
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: _buildSecondaryButton(
                          icon: Icons.add_to_queue,
                          label: '稍后观看',
                          onPressed: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('稍后观看功能开发中'),
                                duration: Duration(seconds: 1),
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              );
            }
          },
        ),
      ),
    );
  }

  Widget _buildPlayButton() {
    return ElevatedButton.icon(
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('播放功能开发中'),
                    duration: Duration(seconds: 1),
                  ),
                );
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor,
                foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
                ),
        elevation: 3,
              ),
      icon: const Icon(Icons.play_arrow, size: 20),
              label: const Text(
                '立即播放',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
          fontSize: 14,
                ),
              ),
    );
  }

  Widget _buildFavoriteButton() {
    return FavoriteButton(
              anime: anime!,
              showLabel: true,
              onFavoriteChanged: () {
                // 收藏状态变化后的处理
              },
    );
  }

  Widget _buildSecondaryButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
  }) {
    return OutlinedButton(
      onPressed: onPressed,
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(vertical: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        side: BorderSide(color: Colors.grey[300]!),
      ),
        child: Column(
        mainAxisSize: MainAxisSize.min,
          children: [
          Icon(icon, size: 16, color: Colors.grey[600]),
          const SizedBox(height: 2),
          Text(
            label,
              style: TextStyle(
              fontSize: 11,
              color: Colors.grey[700],
                ),
              ),
          ],
      ),
    );
  }

  Widget _buildSynopsisSection() {
    return _ExpandableSynopsis(anime: anime!);
  }

  Widget _buildEpisodesList() {
    // 模拟集数数据，实际应用中应该从API获取
    final episodes = List.generate(
      anime!.episodes > 0 ? anime!.episodes : 12,
      (index) => {
        'number': index + 1,
        'title': '第${index + 1}话',
        'duration': '${20 + (index % 5) * 2}分钟',
        'isWatched': index < 3, // 前3集已观看
      },
    );

    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Text(
                  '选集',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF2C3E50),
                  ),
                ),
                const Spacer(),
                Text(
                  '共${episodes.length}话',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 120,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: episodes.length,
              itemBuilder: (context, index) {
                final episode = episodes[index];
                final isWatched = episode['isWatched'] as bool;
                
                return Container(
                  width: 100,
                  margin: const EdgeInsets.only(right: 12),
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      borderRadius: BorderRadius.circular(8),
                      onTap: () {
                        // TODO: 播放对应集数
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('播放${episode['title']}'),
                            duration: const Duration(seconds: 1),
                          ),
                        );
                      },
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: isWatched 
                              ? Colors.grey[100] 
                              : Colors.transparent,
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: Colors.grey[300]!,
                            width: 1,
                          ),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            if (isWatched)
                              Icon(
                                Icons.check_circle,
                                color: Theme.of(context).primaryColor,
                                size: 16,
                              )
                            else
                              Icon(
                                Icons.play_circle_outline,
                                color: Colors.grey[600],
                                size: 16,
                              ),
                            const SizedBox(height: 4),
                            Text(
                              episode['title'] as String,
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                                color: isWatched 
                                    ? Theme.of(context).primaryColor
                                    : Colors.grey[700],
                              ),
                              textAlign: TextAlign.center,
                            ),
                            const SizedBox(height: 2),
                            Text(
                              episode['duration'] as String,
                              style: TextStyle(
                                fontSize: 10,
                                color: Colors.grey[500],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildRecommendations() {
    return Container(
      margin: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                const Text(
              '相关推荐',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Color(0xFF2C3E50),
              ),
            ),
                if (isLoadingRecommendations) ...[
                  const SizedBox(width: 8),
                  const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                ],
              ],
            ),
          ),
          
          if (isLoadingRecommendations)
            const SizedBox(
            height: 140,
              child: Center(
                child: CircularProgressIndicator(),
              ),
            )
          else if (recommendations.isEmpty)
            const SizedBox(
              height: 140,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.search_off, size: 48, color: Colors.grey),
                    SizedBox(height: 8),
                    Text(
                      '暂无相关推荐',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
            )
          else
            SizedBox(
              height: 160, // 简化后调整高度
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
                itemCount: recommendations.length,
              itemBuilder: (context, index) {
                  final recommendedAnime = recommendations[index];
                  final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
                    title: recommendedAnime.title,
                    titleJapanese: recommendedAnime.titleJapanese,
                    titleEnglish: recommendedAnime.titleEnglish,
                    titleSynonyms: recommendedAnime.titleSynonyms,
                  );
                  
                  return GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(
                        context,
                        '/detail',
                        arguments: {'id': recommendedAnime.id},
                      );
                    },
                    child: Container(
                      width: 120,
                  margin: const EdgeInsets.only(right: 12),
                  child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                          // 动漫封面
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.grey[300],
                            borderRadius: BorderRadius.circular(8),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withValues(alpha: 0.1),
                                    blurRadius: 4,
                                    offset: const Offset(0, 2),
                                  ),
                                ],
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: recommendedAnime.imageUrl.isNotEmpty
                                    ? CachedNetworkImage(
                                        imageUrl: recommendedAnime.imageUrl,
                              fit: BoxFit.cover,
                                        placeholder: (context, url) => Container(
                                          color: Colors.grey[300],
                                          child: const Center(
                                            child: CircularProgressIndicator(),
                            ),
                          ),
                                        errorWidget: (context, url, error) => Container(
                                          color: Colors.grey[300],
                                          child: const Icon(Icons.image_not_supported),
                        ),
                                      )
                                    : Container(
                                        color: Colors.grey[300],
                                        child: const Icon(Icons.image_not_supported),
                      ),
                              ),
                            ),
                          ),
                          
                      const SizedBox(height: 8),
                          
                          // 标题
                      Text(
                            chineseTitle,
                        style: const TextStyle(
                          fontSize: 12,
                              fontWeight: FontWeight.w600,
                              color: Color(0xFF2C3E50),
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                            textAlign: TextAlign.center,
                      ),
                    ],
                      ),
                  ),
                );
              },
            ),
          ),
          
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildInfoChip(String label, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 8,
        vertical: 4,
      ),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w500,
          color: color,
        ),
      ),
    );
  }

  Color _getThemeColor(int id) {
    final colors = [
      Colors.blue,
      Colors.purple,
      Colors.orange,
      Colors.green,
      Colors.red,
    ];
    return colors[id % colors.length];
  }

  Color _getScoreColor(double score) {
    if (score >= 9.0) return Colors.green;
    if (score >= 8.0) return Colors.orange;
    if (score >= 7.0) return Colors.blue;
    return Colors.grey;
  }

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'airing':
      case 'currently airing':
        return Colors.green;
      case 'finished airing':
      case 'completed':
        return Colors.blue;
      case 'not yet aired':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status.toLowerCase()) {
      case 'airing':
      case 'currently airing':
        return '连载中';
      case 'finished airing':
      case 'completed':
        return '已完结';
      case 'not yet aired':
        return '即将上线';
      default:
        return status;
    }
  }

  String _getScoreDescription(double score) {
    if (score >= 9.0) return '神作';
    if (score >= 8.5) return '优秀';
    if (score >= 8.0) return '良好';
    if (score >= 7.5) return '不错';
    if (score >= 7.0) return '一般';
    return '普通';
  }

  String _formatNumber(num number) {
    if (number is int) {
      if (number >= 1000000) {
        return '${(number / 1000000).toStringAsFixed(1)}M';
      } else if (number >= 1000) {
        return '${(number / 1000).toStringAsFixed(1)}K';
      } else {
        return number.toString();
      }
    } else if (number is num) {
      return number.toString();
    } else {
      throw Exception('Invalid number format');
    }
  }

  String _getRatingText(String rating) {
    switch (rating) {
      case 'G - All Ages':
        return '全年龄';
      case 'PG - Children':
        return '儿童适宜';
      case 'PG-13 - Teens 13 or older':
        return '13岁以上';
      case 'R - 17+ (violence & profanity)':
        return '17岁以上（暴力内容）';
      case 'R+ - Mild Nudity':
        return '17岁以上（轻度裸体）';
      case 'Rx - Hentai':
        return '成人内容';
      default:
        return rating;
    }
  }

  void _showFullScreenImage() {
    if (anime!.imageUrl.isEmpty) return;
    
    showDialog(
      context: context,
      barrierColor: Colors.black,
      builder: (context) => Dialog.fullscreen(
        backgroundColor: Colors.black,
        child: Stack(
          children: [
            Center(
              child: InteractiveViewer(
                minScale: 0.5,
                maxScale: 3.0,
                child: CachedNetworkImage(
                  imageUrl: anime!.imageUrl,
                  fit: BoxFit.contain,
                  placeholder: (context, url) => const Center(
                    child: CircularProgressIndicator(color: Colors.white),
                  ),
                  errorWidget: (context, url, error) => const Center(
                    child: Icon(Icons.error, color: Colors.white, size: 80),
                  ),
                ),
              ),
            ),
            Positioned(
              top: 40,
              right: 20,
              child: IconButton(
                onPressed: () => Navigator.pop(context),
                icon: const Icon(Icons.close, color: Colors.white, size: 30),
              ),
            ),
            Positioned(
              bottom: 40,
              left: 20,
              right: 20,
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.7),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  ChineseTitleMapper.getBestChineseTitle(
                    title: anime!.title,
                    titleJapanese: anime!.titleJapanese,
                    titleEnglish: anime!.titleEnglish,
                    titleSynonyms: anime!.titleSynonyms,
                  ),
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatAiredTime(String airedTime) {
    // 简化播出时间格式，例如：从 "1998-04-03T00:00:00+00:00 至 1999-04-24T00:00:00+00:00" 
    // 简化为 "1998-04-03 至 1999-04-24"
    try {
      final parts = airedTime.split(' 至 ');
      if (parts.length == 2) {
        final startDate = parts[0].split('T')[0];
        final endDate = parts[1].split('T')[0];
        return '$startDate 至 $endDate';
      }
      return airedTime.split('T')[0]; // 如果只有一个日期
    } catch (e) {
      return airedTime; // 如果解析失败，返回原始值
    }
  }

  Widget _buildDetailInfoRow({
    required IconData icon,
    required String label,
    required String value,
    bool isLink = false,
    VoidCallback? onTap,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(
          icon,
          size: 16,
          color: Colors.grey[600],
        ),
        const SizedBox(width: 8),
        Expanded(
          flex: 2,
          child: Text(
            label,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w600,
              color: Colors.grey[700],
            ),
          ),
        ),
        Expanded(
          flex: 3,
          child: isLink && onTap != null
              ? GestureDetector(
                  onTap: onTap,
                  child: Text(
                    value,
                    style: TextStyle(
                      fontSize: 12,
                      color: Theme.of(context).primaryColor,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                )
              : Text(
                  value,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.black87,
                  ),
                ),
        ),
      ],
    );
  }

  String _getSeasonText(String season) {
    switch (season.toLowerCase()) {
      case 'spring':
        return '春季';
      case 'summer':
        return '夏季';
      case 'fall':
      case 'autumn':
        return '秋季';
      case 'winter':
        return '冬季';
      default:
        return season;
    }
  }
}

/// 可展开的简介组件
class _ExpandableSynopsis extends StatefulWidget {
  final Anime anime;

  const _ExpandableSynopsis({required this.anime});

  @override
  State<_ExpandableSynopsis> createState() => _ExpandableSynopsisState();
}

class _ExpandableSynopsisState extends State<_ExpandableSynopsis> {
  bool _isExpanded = false;
  static const int _collapsedMaxLines = 4;

  @override
  Widget build(BuildContext context) {
    // 优先显示API返回的真实简介，而不是中文映射的占位符
    String displaySynopsis = '';
    bool showChineseFirst = false;
    bool hasRealSynopsis = false;
    
    // 首先检查原始简介是否是真实内容
    if (widget.anime.synopsis.isNotEmpty && 
        widget.anime.synopsis != '暂无简介' &&
        !widget.anime.synopsis.contains('暂无简介') &&
        !widget.anime.synopsis.contains('本作品讲述了一个精彩的故事') &&
        widget.anime.synopsis.trim().length > 10) {
      displaySynopsis = widget.anime.synopsis;
      hasRealSynopsis = true;
      showChineseFirst = false;
    } else {
      // 如果原始简介不可用，尝试获取中文简介
      final chineseSynopsis = ChineseTitleMapper.getChineseSynopsis(
        widget.anime.title,
        widget.anime.synopsis,
      );
      
      if (chineseSynopsis.isNotEmpty && 
          chineseSynopsis != '暂无中文简介' && 
          chineseSynopsis != '暂无简介' &&
          !chineseSynopsis.contains('本作品讲述了一个精彩的故事') &&
          !chineseSynopsis.contains('暂无') &&
          chineseSynopsis.trim().length > 20) {
        displaySynopsis = chineseSynopsis;
        hasRealSynopsis = true;
        showChineseFirst = true;
      } else {
        // 如果都没有有效内容，显示默认提示
        displaySynopsis = '暂无简介信息，建议查看官方网站获取详细介绍';
        hasRealSynopsis = false;
      }
    }

    return Card(
      margin: const EdgeInsets.all(16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Text(
                  '简介',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                if (hasRealSynopsis && displaySynopsis.length > 100)
                  TextButton.icon(
                    onPressed: () {
                      setState(() {
                        _isExpanded = !_isExpanded;
                      });
                    },
                    icon: Icon(
                      _isExpanded ? Icons.expand_less : Icons.expand_more,
                      size: 16,
                    ),
                    label: Text(
                      _isExpanded ? '收起' : '展开',
                      style: const TextStyle(fontSize: 12),
                    ),
                    style: TextButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 12),
            
            // 主要简介内容
            AnimatedSize(
              duration: const Duration(milliseconds: 300),
              child: Text(
                displaySynopsis,
                style: TextStyle(
                  fontSize: 14,
                  height: 1.6,
                  color: hasRealSynopsis 
                      ? Colors.grey[700]
                      : Colors.grey[500],
                ),
                maxLines: hasRealSynopsis && _isExpanded ? null : (hasRealSynopsis ? _collapsedMaxLines : null),
                overflow: hasRealSynopsis && !_isExpanded ? TextOverflow.ellipsis : TextOverflow.visible,
              ),
            ),
            
            // 如果显示的是中文简介，且原文简介不同，提供查看原文选项
            if (showChineseFirst && 
                hasRealSynopsis &&
                displaySynopsis != widget.anime.synopsis && 
                widget.anime.synopsis.isNotEmpty &&
                widget.anime.synopsis != '暂无简介' &&
                widget.anime.synopsis.trim().length > 10)
              Padding(
                padding: const EdgeInsets.only(top: 12),
                child: TextButton.icon(
                  onPressed: () {
                    _showOriginalSynopsis();
                  },
                  icon: const Icon(Icons.translate, size: 16),
                  label: const Text('查看原文简介'),
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    minimumSize: Size.zero,
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  void _showOriginalSynopsis() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('原文简介'),
        content: SizedBox(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Text(
              widget.anime.synopsis,
              style: const TextStyle(fontSize: 14, height: 1.6),
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }
} 